package com.eduplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eduplatform.entity.Course;
import com.eduplatform.mapper.CourseMapper;
import com.eduplatform.service.CourseService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Override
    public Page<Course> listCourses(Integer page, Integer size) {
        Page<Course> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<Course> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Course::getStatus, 1); // Only published courses
        queryWrapper.orderByDesc(Course::getCreateTime);

        return this.page(pageParam, queryWrapper);
    }

    @Override
    public Page<Course> listCoursesWithFilters(Integer page, Integer size, String keyword,
            Long subjectId, Integer level, String type) {
        Page<Course> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<Course> queryWrapper = new LambdaQueryWrapper<>();

        // 基本筛选条件
        queryWrapper.eq(Course::getStatus, 1); // 只查询已发布的课程

        // 关键词搜索
        if (!StringUtils.isEmpty(keyword)) {
            queryWrapper.and(wrapper -> wrapper.like(Course::getTitle, keyword)
                    .or()
                    .like(Course::getDescription, keyword));
        }

        // 按学科筛选
        if (subjectId != null && subjectId > 0) {
            queryWrapper.eq(Course::getSubjectId, subjectId);
        }

        // 按难度筛选
        if (level != null && level > 0) {
            queryWrapper.eq(Course::getLevel, level);
        }

        // 排序
        queryWrapper.orderByDesc(Course::getCreateTime);

        return this.page(pageParam, queryWrapper);
    }

    @Override
    public Page<Course> listCoursesByTeacher(Long teacherId, Integer page, Integer size) {
        Page<Course> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<Course> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Course::getTeacherId, teacherId);
        queryWrapper.orderByDesc(Course::getCreateTime);

        return this.page(pageParam, queryWrapper);
    }
}